<?php
 /**
 * 共用类，公用的处理函数都可以写在个类
 *
 * LICENSE:
 * @author $Id$
 * @since      Release 1.0.0
 * @copyright  Copyright (c) 2010-2011 Mumayi.com Inc. (http://www.mumayi.com)
*/
class Custom_Controller_Plugin_Common extends Zend_Controller_Plugin_Abstract
{

		public function __construct() {


		}

		/**
		 * 生成不重复的值
		 * @param unknown_type $word
		 * @param unknown_type $length
		 * @param unknown_type $frontkey
		 * @param unknown_type $backkey
		 * @return Ambigous <string>
		 */
		public function ShortWord($word,$length='10',$frontkey='www.mumayi.com',$backkey='123@789') {

			$String = array (
					'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
					'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
					'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
					'y', 'z', '0', '1', '2', '3', '4', '5',
					'6', '7', '8', '9', 'A', 'B', 'C', 'D',
					'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
					'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
					'U', 'V', 'W', 'X', 'Y', 'Z'
			);
			$hex = md5($frontkey.$word.$backkey);
			$hexLen = strlen($hex);
			$subHexLen = $hexLen/8;
			$outstring = array();

			for ($i = 0; $i < $subHexLen; $i++) {
				$subHex = substr ($hex, $i*8, 7);
				$int = 0x3FFFFFFF & (1 * ('0x'.$subHex));
				$out = '';

				for ($j = 0; $j <$length; $j++) {
					$val = 0x0000001F & $int;
					if($j==2||$j==7){
						$out .= $String[$val ^ 32];
					}elseif($j==0){
						$out .= $String[$val ^ 40];
					}else{
						$out .= $String[$val ^ 7];
					}
					$int = $int >>2;
				}

				if(strlen($out)==$length){
					$outstring[] = $out;
				}
			}
			return $outstring[0];
		}


		/**
		 * 去掉html
		 * @param unknown_type $content
		 * @param unknown_type $allowtags
		 * @return Ambigous <mixed, string>
		 */
		function ClearHtml($content,$allowtags='') {
			$content = preg_replace("/<!--[^>]*-->/i", "", $content);//注释内容
			$content = preg_replace("/style=.+?['|\"]/i",'',$content);//去除样式
			$content = preg_replace("/class=.+?['|\"]/i",'',$content);//去除样式
			$content = preg_replace("/id=.+?['|\"]/i",'',$content);//去除样式
			$content = preg_replace("/lang=.+?['|\"]/i",'',$content);//去除样式
			$content = preg_replace("/width=.+?['|\"]/i",'',$content);//去除样式
			$content = preg_replace("/height=.+?['|\"]/i",'',$content);//去除样式
			$content = preg_replace("/border=.+?['|\"]/i",'',$content);//去除样式
			$content = preg_replace("/size=.+?['|\"]/i",'',$content);//去除样式
			if($allowtags){
				$content = strip_tags($content,$allowtags);
			}else{
				$content = strip_tags($content);
			}
			return $content;
		}


		function ShowMsg($msg,$gourl,$onlymsg=0,$limittime=0)
		{
			if(empty($GLOBALS['cfg_phpurl'])) $GLOBALS['cfg_phpurl'] = '..';

			$htmlhead  = "<html>\r\n<head>\r\n<title>都市家友情提示信息</title>\r\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\" />\r\n";
			$htmlhead .= "<base target='_self'/>\r\n<style>div{line-height:160%;}</style></head>\r\n<body leftmargin='0' topmargin='0'>".(isset($GLOBALS['ucsynlogin']) ? $GLOBALS['ucsynlogin'] : '')."\r\n<center>\r\n<script>\r\n";
			$htmlfoot  = "</script>\r\n</center>\r\n</body>\r\n</html>\r\n";

			$litime = ($limittime==0 ? 1000 : $limittime);
			$func = '';

			if($gourl=='-1'){
				if($limittime==0) $litime = 5000;
				$gourl = "javascript:history.go(-1);";
			}

			if($gourl=='' || $onlymsg==1){
				$msg = "<script>alert(\"".str_replace("\"","“",$msg)."\");</script>";
			}else{
				//当网址为:close::objname 时, 关闭父框架的id=objname元素
				if(preg_match("/^close\:\:$/i",$gourl)){
					$tgobj = trim(preg_replace("/^close\:\:$/i", '', $gourl));
					$gourl = 'javascript:;';
					$func .= "window.parent.document.getElementById('{$tgobj}').style.display='none';\r\n";
				}

				$func .= "      var pgo=0;
				function JumpUrl(){
				if(pgo==0){ location='$gourl'; pgo=1; }
			}\r\n";
				$rmsg = $func;
				$rmsg .= "document.write(\"<br /><div style='width:450px;padding:0px;border:1px solid #D1DDAA;'>";
				$rmsg .= "<div style='padding:6px;font-size:12px;border-bottom:1px solid #D1DDAA;background:#DBEEBD url({$GLOBALS['cfg_phpurl']}/img/wbg.gif)';'><b>都市家友情提示信息！</b></div>\");\r\n";
				$rmsg .= "document.write(\"<div style='height:130px;font-size:10pt;background:#ffffff'><br />\");\r\n";
				$rmsg .= "document.write(\"".str_replace("\"","“",$msg)."\");\r\n";
				$rmsg .= "document.write(\"";

						if($onlymsg==0){
							if( $gourl != 'javascript:;' && $gourl != ''){
							$rmsg .= "<br /><a href='{$gourl}'>如果你的浏览器没反应，请点击这里...</a>";
							$rmsg .= "<br/></div>\");\r\n";
							$rmsg .= "setTimeout('JumpUrl()',$litime);";
							}else{
							$rmsg .= "<br/></div>\");\r\n";
							}
			}else{
				$rmsg .= "<br/><br/></div>\");\r\n";
			}
				$msg  = $htmlhead.$rmsg.$htmlfoot;
			}
			echo $msg;
		}

		function GetPicImages($img){
			$pos= stripos($img, 'img_mumayi');
			$imgurl=$this->imgUrl();
			if($pos===false){
				$newimg=$imgurl.'/android/images'.$img;
			}else{
				$newimg=$this->GetRandImages($img);
			}
			return $newimg;
		}

		function GetRandImages($img){
			$imgsName=array('imga','imgb');
			$randoms= array_rand($imgsName);
			$randnames = $imgsName[$randoms];
			$imageurl = 'http://'.$randnames.'.mumayi.com';
			//处理$imageurl 去掉uploads
			$images=$imageurl.str_replace("uploads/", "",$img);
			return $images;
		}

		/*
		 随机取附件图片地址
		*/
		function imgUrl()
		{
			//随机取图片地址
			$imgname=array('imga','imgb');
			$random = array_rand($imgname);
			$randname = $imgname[$random];
			$imgurl='http://'.$randname.'.mumayi.com';
			return $imgurl;
		}

        //用户IP获取(无法获取默认为北京)
	    function GetIP(){
	        if(!empty($_SERVER["HTTP_CLIENT_IP"]))
	           $cip = $_SERVER["HTTP_CLIENT_IP"];
	        else if(!empty($_SERVER["HTTP_X_FORWARDED_FOR"]))
	           $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
	        else if(!empty($_SERVER["REMOTE_ADDR"]))
	           $cip = $_SERVER["REMOTE_ADDR"];
	        else
	           $cip = "58.30.0.0";
	        return $cip;
	    }

	    //防注入
	    function mAddslashes($var) {
	        if (! get_magic_quotes_gpc ()) {
	            if (is_array ( $var )) {
	                foreach ( $var as $key => $val ) {
	                    $var [$key] = mAddslashes ( $val );
	                }
	            } else {
	                $var = addslashes ( $var );
	            }
	        }
	        return $var;
	    }
	    //密码生成
	    function ucPass($pass,$salt) {
	        $pwd = md5(md5($pass).$salt);
	        return $pwd;
	    }
	    //密码匹配
	    function ucPassC($pass,$salt) {
	        $pwd = md5(md5($pass).$salt);
	        return $pwd;
	    }
	    //json编码
	    function bJson($arr) {
	        return Zend_Json::encode($arr);
	    }
	    //json解码
	    function xJson($arr) {
	        return Zend_Json::decode($arr);
	    }
	    //json转数组
	    function jsonarray($json,$key) {
	        $jsonarr = $this->xJson(stripslashes($json));
	        return $jsonarr[$key];
	    }
	    //邮箱识别
	    function is_email($email){
	        return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-]+(\.\w+)+$/", $email);
	    }
	    //手机号识别
	    function is_mobile($str){
	      if(strlen($str)==11 && substr($str,0,1)==1) {
	          return true;
	      }else{
	          return false;
	      }
	    }
	    //随机用户名
	    function randUser() {
	        $username = intval(file_get_contents('user.ini'));
	        $userarr = array('xname'=>'小蚂蚁'.$username++);
	        file_put_contents('user.ini',$username);
	        return $userarr;
	    }
	    //随机注册码
	    function randSalt() {
	        return substr(uniqid(rand()), -6);
	    }
	    //session id
	    function sessionUid() {
	        return md5(substr(uniqid(rand()), -6));
	    }
	    //头像
	    function regAvatar($uid) {
	        return 'http://bbs.mumayi.com/uc_server/avatar.php?uid='.$uid.'&size=middle';
	    }
	    //空间
	    function regSpace($uid) {
	        return "http://bbs.mumayi.com/space-uid-".$uid.".html";
	    }
	    //转码
	    function strIconvU_G($str) {
	        return iconv( "UTF-8","GBK",$str);
	    }
	    //转码2
	    function strIconvG_U($str) {
	        return iconv("GBK","UTF-8",$str);
	    }
	    //时间差
	    function timeNum($start,$end,$interval) {
	        if($start && $end) {
	            $num = $end-$start;
	            if($num>$interval) {
	                return $num;
	            }else{
	                return false;
	            }
	        }else{
	            return false;
	        }
	    }
	    /*
		 * 随机密码
		 */
	    function randPass( $length = 6 )
	    {
	        // 密码字符集，可任意添加你需要的字符
	        $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
	        'i', 'j', 'k', 'l','m', 'n', 'o', 'p', 'q', 'r', 's',
	        't', 'u', 'v', 'w', 'x', 'y','z', 'A', 'B', 'C', 'D',
	        'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L','M', 'N', 'O',
	        'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y','Z',
	        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');

	        // 在 $chars 中随机取 $length 个数组元素键名
	        $keys = array_rand($chars, $length);
	        $password = '';
	        for($i = 0; $i < $length; $i++)
	        {
	            // 将 $length 个数组元素连接成字符串
	            $password .= $chars[$keys[$i]];
	        }
	        return $password;
	    }
	    /*
		 * 随机密码(密码找回)
		 */
	    function findPass()
	    {
	        // 密码字符集，可任意添加你需要的字符
	        $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h','i', 'j', 'k', 'l','m', 'n', 'o', 'p', 'q', 'r', 's','t', 'u', 'v', 'w', 'x', 'y','z');
	         $nums = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');

	        // 在 $chars 中随机取 $length 个数组元素键名
	        $keys1 = array_rand($chars,2);
			$keys2 = array_rand($nums,5);
	        $password = '';
	        for($i = 0; $i < 2; $i++)
	        {
	            // 将 $length 个数组元素连接成字符串
	            $password .= $chars[$keys1[$i]];
	        }
			for($i = 0; $i < 5; $i++)
	        {
	            // 将 $length 个数组元素连接成字符串
	            $password .= $nums[$keys2[$i]];
	        }
	        return $password;
	    }
	    /*
		 * 手机号加*号
		 */
	    function phonereplace($phone){
		    return str_replace(substr($phone,3,4),'****',$phone);
	    }
	    /*
		 * 遍历生成文件夹
		 */
	    function mk_dir($path, $rights = 0777){
	      $folder_path = array(
	        strstr($path, '.') ? dirname($path) : $path);

	      while(!@is_dir(dirname(end($folder_path)))
	              && dirname(end($folder_path)) != '/'
	              && dirname(end($folder_path)) != '.'
	              && dirname(end($folder_path)) != '')
	        array_push($folder_path, dirname(end($folder_path)));

	      while($parent_folder_path = array_pop($folder_path))
	        if(!@mkdir($parent_folder_path, $rights))
	          user_error("Can't create folder \"$parent_folder_path\".");
	    }


        //邮箱检测
        function checkEmail($inAddress)   {
            return (@ereg("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+",$inAddress));
        }






}